package com.common.app.utls

import android.util.Base64
import android.util.Log
import org.json.JSONObject
import org.zero.brotlilib.dec.BrotliInputStream
import org.zero.brotlilib.enc.BrotliOutputStream
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.charset.StandardCharsets

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：11/6/2025
 *
 * 描述：
 *
 * 修订历史：
 *
 */
object BrotliCompressionEx {
    @Throws(IOException::class)
    fun compressFile(inputPath: String, outputPath: String) {
        FileInputStream(inputPath).use { fis ->
            BrotliOutputStream(FileOutputStream(outputPath)).use { bos ->
                val buffer = ByteArray(1024)
                var length: Int
                while (fis.read(buffer).also { length = it } != -1) {
                    bos.write(buffer, 0, length)
                }
            }
        }
    }

    @Throws(IOException::class)
    fun decompressFile(inputPath: String?, outputPath: String?) {
        BrotliInputStream(FileInputStream(inputPath)).use { bis ->
            FileOutputStream(outputPath).use { fos ->
                val buffer = ByteArray(1024)
                var length: Int
                while (bis.read(buffer).also { length = it } != -1) {
                    fos.write(buffer, 0, length)
                }
            }
        }
    }

    /**
     * 压缩字符串
     * @param input 要压缩的字符串
     * @return 压缩后的字节数组
     */
    @Throws(IOException::class)
    fun compressString(input: String): ByteArray {
        val inputBytes = input.toByteArray(StandardCharsets.UTF_8)
        val outputStream = ByteArrayOutputStream()

        BrotliOutputStream(outputStream).use { bos ->
            bos.write(inputBytes)
            bos.flush()
        }

        return outputStream.toByteArray()
    }

    /**
     * 解压缩字节数组为字符串
     * @param compressedData 压缩后的字节数组
     * @return 解压缩后的字符串
     */
    @Throws(IOException::class)
    fun decompressToString(compressedData: ByteArray): String {
        val inputStream = ByteArrayInputStream(compressedData)
        val outputStream = ByteArrayOutputStream()

        BrotliInputStream(inputStream).use { bis ->
            val buffer = ByteArray(1024)
            var length: Int
            while (bis.read(buffer).also { length = it } != -1) {
                outputStream.write(buffer, 0, length)
            }
        }

        return String(outputStream.toByteArray(), StandardCharsets.UTF_8)
    }

    fun compressJsonByBrotli(jsonString:String) :String {
        val compressedData:ByteArray?
        try {
            // 2. 压缩JSON字符串
            compressedData = BrotliCompressionEx.compressString(jsonString)

            Log.e("EnUpSignDataUtil", "SOU: compressJsonByBrotli-------decompressedJson： ${compressedData}")

//        // 3. 可以将压缩后的数据用于网络传输或存储
//        // 例如，转换为Base64字符串进行传输
//        val base64Encoded = encodeToString(compressedData, android.util.Base64.DEFAULT)
//        // 4. 解压缩示例
//        // 先将Base64字符串解码回字节数组
//        val decodedBytes = decode(base64Encoded, android.util.Base64.DEFAULT)
//        // 然后解压缩
//        val decompressedJson = BrotliCompressionEx.decompressToString(decodedBytes)
//
//        Log.e("EnUpSignDataUtil", "YQ: compressJsonExample2-------decompressedJson： ${decompressedJson}")

            return Base64.encodeToString(compressedData, Base64.DEFAULT)

        } catch (e: Exception) {
            e.printStackTrace()
            return jsonString
        }
    }



    // 按Unicode码点升序排序字段并按照key=value&key=value格式拼接，排除静态字段
    fun sortAndConcatenateFieldsByJo(jsonObject: JSONObject): String {
        // 获取JSONObject中的所有键
        val keys = jsonObject.keys()
        val keyList = mutableListOf<String>()

        // 将所有键添加到列表中
        while (keys.hasNext()) {
            val key = keys.next()
            keyList.add(key)
        }

        // 按Unicode码点升序排序键
        val sortedKeys = keyList.sorted()

        // 构建排序后的字段值字符串，格式为key=value&key=value
        return sortedKeys.joinToString("&") { key ->
            val value = jsonObject.optString(key, "")
            "$key=$value"
        }
    }

    /**
     * 压缩字符串
     * @param input 要压缩的字符串
     * @return 压缩后的字节数组
     */
    fun compressStringByObd(input: String): ByteArray {
        val inputBytes = input.toByteArray(StandardCharsets.UTF_8)
        val outputStream = ByteArrayOutputStream()

        BrotliOutputStream(outputStream).use { bos ->
            bos.write(inputBytes)
            bos.flush()
        }

        return outputStream.toByteArray()
    }

    /**
     * 解压缩字节数组为字符串
     * @param compressedData 压缩后的字节数组
     * @return 解压缩后的字符串
     */
    fun decompressToStringByObd(compressedData: ByteArray): String {
        // 使用Brotli库直接解压缩
        val inputStream = ByteArrayInputStream(compressedData)
        val outputStream = ByteArrayOutputStream()

        org.brotli.dec.BrotliInputStream(inputStream).use { brotliInputStream ->
            val buffer = ByteArray(1024)
            var length: Int
            while (brotliInputStream.read(buffer).also { length = it } != -1) {
                outputStream.write(buffer, 0, length)
            }
        }

        return String(outputStream.toByteArray(), StandardCharsets.UTF_8)
    }
}